package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import common.Util;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");

        //1.先监测当前是否登录
        User user = Util.checkLoginStatus(req);
        if (user == null) {
            String html = "您尚未登录!";
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write(html);
            return;
        }

        //2.根据是否能获取到blogId，对应的返回用户名或作者名
        String blogId = req.getParameter("blogId");
        if (blogId == null) {
            //获取当前登录用户的信息
            String jsonString = objectMapper.writeValueAsString(user);
            resp.getWriter().write(jsonString);
        } else {
            //获取指定文章的作者的信息
            //根据blogId在数据库里查到对应的userId,再根据这个userId拿到对应的user详情
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (blog == null) {
                String html = "指定的博客不存在!";
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write(html);
                return;
            }
            UserDao userDao = new UserDao();
            User author = userDao.selectById(blog.getUserId());
            //把isYourBlog字段给设置进去
            author.setIsYourBlog(author.getUserId() == user.getUserId() ? 1 : 0);
            String jsonString = objectMapper.writeValueAsString(author);
            resp.getWriter().write(jsonString);
        }
    }
}
